/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */
package com.fuyao.cloud.admin.message.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.admin.message.mapper.MessageCtiMapper;
import com.fuyao.cloud.admin.message.service.MessageCtiService;
import com.fuyao.cloud.admin.message.service.MessageManagementService;
import com.fuyao.cloud.common.data.datascope.DataScope;
import com.fuyao.cloud.common.data.datascope.PageSelectScope;
import com.fuyao.cloud.message.entity.MessageCti;
import com.fuyao.cloud.message.entity.MessageManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息分类
 *
 * @author liyue
 * @date 2022-04-22 17:27:25
 */
@Service
public class MessageCtiServiceImpl extends ServiceImpl<MessageCtiMapper, MessageCti> implements MessageCtiService {

    @Autowired
    @Lazy
    private MessageManagementService managementService;

    @Override
    public boolean save(MessageCti entity) {
        setEntityAttributes(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(MessageCti entity) {
        setEntityAttributes(entity);
        return super.updateById(entity);
    }

    @Override
    public boolean removeById(Serializable id) {
        LambdaQueryWrapper<MessageCti> lambdaQueryWrapper = Wrappers.lambdaQuery();
        Long messageCtiCount = this.getBaseMapper().selectCount(lambdaQueryWrapper.eq(MessageCti::getParentId, id));
        AssertUtil.isTrue(messageCtiCount == 0, "包含子分类，请先删除子分类。");

        long count = managementService.count(Wrappers.<MessageManagement>lambdaQuery().eq(MessageManagement::getCtiId, id));
        AssertUtil.isTrue(count == 0, "当前分类有关联消息管理，无法删除。");

        return super.removeById(id);
    }

    @Override
    public List<Tree<Long>> selectTree() {
        List<MessageCti> messageCtis = this.getBaseMapper().selectList(Wrappers.emptyWrapper());
        List<Long> regionalOwnIdList = this.getBaseMapper().selectListByScope(Wrappers.emptyWrapper(), new DataScope()).stream()
                .map(MessageCti::getDeptId).collect(Collectors.toList());
        List<TreeNode<Long>> collect = messageCtis.stream()
                .sorted(Comparator.comparing(MessageCti::getCreateTime)).map(cti -> {
                    TreeNode<Long> treeNode = new TreeNode();
                    treeNode.setId(cti.getId());
                    treeNode.setParentId(cti.getParentId());
                    treeNode.setName(cti.getName());
                    treeNode.setWeight(120L);
                    // 有权限不返回标识
                    Map<String, Object> extra = new HashMap<>(8);
                    extra.put("isLock", !regionalOwnIdList.contains(cti.getDeptId()));
                    extra.put("createTime", cti.getCreateTime());
                    treeNode.setExtra(extra);
                    return treeNode;
                }).collect(Collectors.toList());
        return TreeUtil.build(collect, 0L);
    }

    @PageSelectScope("messagecti")
    @Override
    public IPage<MessageCti> page(Page page, Wrapper<MessageCti> query, DataScope dataScope) {
        return this.baseMapper.selectPageByScope(page,query,dataScope);
    }

    private void setEntityAttributes(MessageCti entity) {
        entity.setFullcode(entity.getCode());
        entity.setFullname(entity.getName());
        if (ObjectUtil.isNotEmpty(entity.getParentId()) && entity.getParentId() > 0) {
            MessageCti parent = this.getById(entity.getParentId());
            entity.setParentName(parent.getName());
            String fullCode = StrBuilder.create().append(parent.getFullcode()).append(".").append(entity.getCode()).toString();
            String fullName = StrBuilder.create().append(parent.getFullname()).append(".").append(entity.getName()).toString();
            entity.setFullcode(fullCode);
            entity.setFullname(fullName);
        }
    }
}
